const $headCode = $('#headCode')
	, $headCSS = $('#headCSS')
	, $footerCode = $('#footerCode')
	, $footerJS = $('#footerJS')

const apiPath = '/api/code/'

async function getCode() {
	try {
		const response = await $.ajax({
			url: `${apiPath}get`,
			method: 'GET',
			dataType: 'json'
		})

		const { code, msg, data } = response

		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		$headCode.val(data.headCode)
		$headCSS.val(data.cssCode)
		$footerCode.val(data.footerCode)
		$footerJS.val(data.jsCode)
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
	}
}

$(document).ready(function (e) {
	getCode()

	const $set = $('#set')
	
	$set.on('click', async e => {
		e.preventDefault()

		const data = {
			headCode: $headCode.val() || null,
			cssCode: $headCSS.val() || null,
			footerCode: $footerCode.val() || null,
			jsCode: $footerJS.val() || null
		}
		
		try {
			const response = await $.ajax({
				url: `${apiPath}set`,
				method: 'POST',
				contentType: 'application/json',
				data: JSON.stringify(data),
				dataType: 'json'
			})

			const { code, msg } = response

			if (code !== 200) {
				showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			} else {
				showNotify(msg, 'success', 5000, 'mdi mdi-check', 'top', 'right')
			}
			getCode()
		} catch (error) {
			showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			console.error('服务器有误: ', error)
		}
	})
})